package top.letscode.adclicker.annotation;

import java.util.List;

import top.letscode.adclicker.ad.AbstractUnion;
import top.letscode.adclicker.site.AbstractSite;
import top.letscode.adclicker.store.SimpleDataStore;
import top.letscode.adclicker.util.Constants;

@SuppressWarnings({"rawtypes"})
public class AnnotationUtil {

  private synchronized static void initSiteInfo() {
    if (SimpleDataStore.containsComponent(Constants.STORE_ANNOTATION_SITE)) {
      return;
    }

    List<Class> siteClassList = AnnotationLoader.load(Site.class, AnnotationLoader.BASE_PACKAGE);
    for (Class classz : siteClassList) {
      try {
        AbstractSite site = (AbstractSite) classz.newInstance();
        String key = site.getClass().getAnnotation(Site.class).name();
        SimpleDataStore.put(Constants.STORE_ANNOTATION_SITE, key, site);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static AbstractSite getSite(String siteName) {
    if (!SimpleDataStore.containsComponent(Constants.STORE_ANNOTATION_SITE)) {
      initSiteInfo();
    }

    return (AbstractSite) SimpleDataStore.get(Constants.STORE_ANNOTATION_SITE, siteName);
  }

  private synchronized static void initUnionInfo() {
    if (SimpleDataStore.containsComponent(Constants.STORE_ANNOTATION_UNION)) {
      return;
    }

    List<Class> siteClassList = AnnotationLoader.load(Union.class, AnnotationLoader.BASE_PACKAGE);
    for (Class classz : siteClassList) {
      try {
        Object obj = classz.newInstance();
        String key = obj.getClass().getAnnotation(Union.class).name();
        SimpleDataStore.put(Constants.STORE_ANNOTATION_UNION, key, obj);
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static AbstractUnion getUnion(String name) {
    if (!SimpleDataStore.containsComponent(Constants.STORE_ANNOTATION_UNION)) {
      initUnionInfo();
    }

    return (AbstractUnion) SimpleDataStore.get(Constants.STORE_ANNOTATION_UNION, name);
  }
}
